package com.dc.datacollect.interceptor;

import com.dc.datacollect.components.cache.Cache;
import com.dc.datacollect.constant.BaseConstant;
import com.dc.datacollect.dto.SysUserDTO;
import com.dc.datacollect.helpers.BeanProvide;
import com.dc.datacollect.helpers.SessionProvide;
import com.dc.datacollect.service.IndexService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;

/**
 * 登录拦截器
 *
 * @author zhuangjie
 * @date 2023/06/19
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    private boolean isFirstIn = true;
    @Autowired
    private BeanProvide beanProvide;

    @Autowired
    private Cache cache;

    @Value("${server.port}")
    private Integer port;


    /**
     * 初始化连接,供构建请求的全路径使用
     *
     * @throws UnknownHostException 未知主机异常
     */
    @PostConstruct
    public void initLink() throws UnknownHostException {
        InetAddress localHost = InetAddress.getLocalHost();
        String hostAddress = localHost.getHostAddress();
        cache.set(BaseConstant.REQUEST_HOST_AND_PORT,hostAddress+":"+port);
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        if (isFirstIn) {
            isFirstIn = false;
            // 将当前服务器的请求host保存到缓存，代码中会使用到当前需要器的地址
            StringBuffer requestURL = request.getRequestURL();
            cache.set(BaseConstant.REQUEST_HOST_AND_PORT,parseUrl(requestURL.toString()));
        }
        String requestURI = request.getRequestURI();
        System.out.println(requestURI+",经过了拦截器");
        // 获取当前服务器
        SysUserDTO loginObject = SessionProvide.getLoginObject();
        // 如果user不为空则放行
        if (loginObject != null) {
            System.out.println("当前用户："+loginObject);
            return true;
        }
        // 尝试记住我登录
        if (beanProvide.inject(IndexService.class).tryRememberMeLogin()) {
            return true;
        }
        // 否则拦截并跳转到登录
        response.sendRedirect(BaseConstant.LOGIN_PAGE);
        return false;
    }
    // 解析 URL 字符串，获取协议、主机名和端口号
    public String parseUrl(String urlString) throws MalformedURLException {
        URL url = new URL(urlString);
        String protocol = url.getProtocol();
        String host = url.getHost();
        int port = url.getPort();
        if (port == -1) {
            port = url.getDefaultPort();
        }
        return protocol + "://" + host + ":" + port;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {

//        SysUserDTO loginObject = SessionProvide.getLoginObject();
//        request.setAttribute("_username",loginObject.getUsername());
//        request.setAttribute("_type",loginObject.getType());
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
    }
}